<?php


namespace App\controllers\v1;


use App\controllers\Base;
use Consts\RedisKey;
use Firebase\JWT\JWT;
use Helper\Config;
use Helper\Output;
use Helper\Mysql;
use Helper\Redis;
use Helper\Reg;


class Customer extends Base
{

    /**
     * 创建一个客户
     * @param $request
     * @param $response
     * @return false|string
     * @throws \Exception
     */
    public function createCustomer($request, $response){

        $params = $request->post;
        //验证所属平台
        $p = Redis::getInstance()->get(RedisKey::KF_PLATFORM_LIST);
        if($p){
            $p = json_decode($p,true);
        }else{
            return Output::json(1027);
        }
        if(!in_array($params['p'],$p)){
            return Output::json(1027);
        }
        //根据唯一标识查询用户是否存在
        $uid = Mysql::getInstance()->where('unique_value',$params['u'])->getValue('customer','id');
        //不存在则创建一个用户
        if(!$uid){
            $data = [
                'unique_value' => $params['u'],
                'nick'         => $request->header['x-real_ip'],
                'from'         => $params['from'],
                'device'       => $params['device'],
                'create_at'    => time(),
            ];
            if($params['account']){
                $data['account'] = $params['account'];
            }
            $res = Mysql::getInstance()->insert('customer',$data);

            if(!$res){
                return Output::json(500);
            }
            $uid = Mysql::getInstance()->getInsertId();

        }

        Redis::getInstance()->hSet(RedisKey::CUSTOMER_NOW_SESS_IP ,'uid:'.$uid , $request->header['x-real_ip']?:'127.0.0.1');
        $jwtConf  = Config::getInstance()->get('jwt');
        $payload = array(
            "iss" => $jwtConf['iss'],
            "aud" => $jwtConf['aud'],
            "iat" => time(),
            "nbf" => time(),
            "exp" => time()+3600*24,
            "data"=> [
                'customer_id'=> $uid
            ]
        );

        $jwt = JWT::encode($payload, $jwtConf['key']);
        $conf = Mysql::getInstance()->get('system_config');
        $conf = array_column($conf,'value_','key_name');

        return Output::json(200,['uid'=> $uid ,'token'=> $jwt ,'conf'=> $conf ]);

    }


}